package com.imooc.mall.exception;

import com.imooc.mall.common.ApiRestResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理统一异常的 handle
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /* 记录日志 */
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /* 抛出异常时，自动收集异常信息 @ExceptionHandler 定义 捕获异常的类型 */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(Exception e) {
        log.error("Default Exception: ", e);
        /* 系统异常 */
        return ApiRestResponse.error(ImoocMallExceptionEnum.SYS_ERROR);
    }

    /* 抛出异常时，自动收集异常信息，抛出 自定义异常 自动捕获 */
    @ExceptionHandler(ImoocMallException.class)
    @ResponseBody
    public Object handleImoocMallException(ImoocMallException e) {
        log.error("ImoocMall Exception: ", e);
        return ApiRestResponse.error(e.getCode(), e.getMessage());
    }

    /* 抛出异常时，自动收集异常信息，抛出 未验证参数异常 自动捕获 */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiRestResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValid  Exception: ", e);
        return handleBindingResult(e.getBindingResult());
    }

    private ApiRestResponse handleBindingResult(BindingResult result) {
        // 把异常处理为对外暴露的提示
        List<String> list = new ArrayList<>();
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            /*for (int i = 0; i < allErrors; i++) {
                ObjectError error = allErrors.get(i);
                String message = error.getDefaultMessage();
                list.addAll(message);
            }*/
            for (ObjectError error : allErrors) {
                String message = error.getDefaultMessage();
                list.add(message);
            }
        }
        if (list.size() == 0) {
            return ApiRestResponse.error(ImoocMallExceptionEnum.REQEUEST_PARAMS_ERROR);
        }

        return ApiRestResponse.error(ImoocMallExceptionEnum.REQEUEST_PARAMS_ERROR.getCode(), list.toString());
    }
}
